from PyQt5.QtGui import QPainter, QPen, QBrush, QColor
from PyQt5.QtWidgets import (
    QApplication,
    QGraphicsScene,
    QGraphicsView,
    QGraphicsItem,
    QMainWindow,
)
from PyQt5.QtCore import Qt, QPointF, QTimer
from math import *


class Vehicle(QGraphicsItem):
    def __init__(self):
        super().__init__()
        self.current_position = QPointF(0, 0)
        self.velocity = 10  # 以像素/秒为单位的速度
        self.current_heading = 0  # 以度为单位的航向
        self.heading_rate = 20  # 航向变化率（度/秒）
        self.color = QColor(Qt.green)
        self.setZValue(1)

    def paint(self, painter, option, widget):
        painter.setPen(QPen(Qt.NoPen))
        painter.setBrush(QBrush(self.color))
        painter.drawEllipse(self.current_position, 10, 10)

    def boundingRect(self):
        return Qt.QRectF(
            self.current_position.x() - 10, self.current_position.y() - 10, 20, 20
        )

    def update_position(self, dt):
        self.current_heading += self.heading_rate * dt
        self.current_position += QPointF(
            self.velocity * dt * cos(self.current_heading),
            -self.velocity * dt * sin(self.current_heading),
        )
        self.prepareGeometryChange()


class Simulation(QMainWindow):
    def __init__(self):
        super().__init__()
        self.scene = QGraphicsScene()
        self.view = QGraphicsView(self.scene)
        self.view.setRenderHint(QPainter.Antialiasing)
        self.setCentralWidget(self.view)
        self.vehicle = Vehicle()
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_scene)
        self.timer.start(100)  # 100毫秒更新一次

        self.scene.addItem(self.vehicle)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Space:
            self.vehicle.heading_rate *= -1
        elif event.key() == Qt.Key_Escape:
            self.close()

    def update_scene(self):
        dt = self.timer.interval() / 1000
        self.vehicle.update_position(dt)
        self.view.setSceneRect(
            self.vehicle.current_position.x() - 200,
            self.vehicle.current_position.y() - 200,
            400,
            400,
        )
        self.view.centerOn(self.vehicle.current_position)


if __name__ == "__main__":
    app = QApplication([])
    sim = Simulation()
    sim.show()
    app.exec_()
